#! /usr/bin/env python
#-******************************************************************************
#
# Copyright (c) 2012-2013,
#  Sony Pictures Imageworks Inc. and
#  Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd.
#
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
# *       Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# *       Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# *       Neither the name of Sony Pictures Imageworks, nor
# Industrial Light & Magic, nor the names of their contributors may be used
# to endorse or promote products derived from this software without specific
# prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
#-******************************************************************************

import os
import re
import sys
import math
import copy
import time
import commands
import traceback

from PyQt4 import QtCore
from PyQt4 import QtGui
from PyQt4 import uic

import imath
import alembic
from lib.alembic_console import AbcConsoleWidget
from lib.alembic_opengl_widget import AbcGLWidget
from lib.alembic_tree_widget import *

kWrapExisting = alembic.Abc.WrapExistingFlag.kWrapExisting

style = """
* {
    background: #777;
    color: #222;
    border: 0px;
}
QGroupBox {
    border: 0px;
    margin: 0px;
    padding: 0px;
    background: #333;
}
QPlainTextEdit {
    background: #222;
    color: #aaabac;
}
QMenu::item:selected {
    color: #aaa;
    background-color: #222;
}
QHeaderView::section {
    background-image: none;
    background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0.0 #aaa, stop: 1.0 #868686);
    color: #111;
    font-weight: bold;
    font-size: 11px;
    font-family: Arial;
    padding-left: 5px;
    border-top: 1px solid #c9c9c9;
    border-right: 1px solid #5e5e5e;
    border-left: 1px solid #a9a9a9;
    border-bottom: 0px solid #282828;
    height: 17px;
    margin: 0px;
}
QTreeView {
    background-color: #373737;
    alternate-background-color: #313131;
    border: 0px;
}
QTreeView::branch {
    width: 0px;
}
QTreeView::item {
    color: #dddddd;
    border-bottom: 1px solid #333;
    border-right-color: transparent;
    border-top-color: transparent;
    height: 20px;
}
QTreeView::item:selected {
    background: #46474b;
    border: 0px;
}
QTreeView::indicator {
    padding-left: -9px;
}
QLineEdit {
    border: 0px;
    background: #666;
    color: #3e6;
}
QToolBar {
    spacing: 0px;
    padding: 4px;
}
QToolButton {
    color: #444;
}
QSplitter {
    background: #777
}
QSplitter::handle:hover {
    background: #7a7;
}
QSplitter::handle:horizontal {
    width: 3px;
}
QSplitter::handle:vertical {
    height: 3px;
}
QProgressBar {
    border: 0px;
    background: #444;
    height: 8px;
}
QProgressBar::chunk {
    background: #4a4;
}
QScrollBar:vertical {
    border: 0ox;
    background: #373737;
    width: 10px;
}
QScrollBar:horizontal {
    border: 0px;
    background: #373737;
    height: 10px;
}
QScrollBar::handle {
    background: #222;
    min-width: 20px;
    border-radius: 5px;
}
QScrollBar::add-line {
    background: #373737;
}
QScrollBar::sub-line {
    background: #373737;
}
"""

class AbcView(QtGui.QMainWindow):
    def __init__(self, filepath=None):
        QtGui.QMainWindow.__init__(self)
        self.setWindowState(QtCore.Qt.WindowActive)
        self.setWindowFlags(QtCore.Qt.Window)
        self.setWindowTitle('AbcView')
        self.setStyle(QtGui.QStyleFactory.create('cleanlooks'))
        self.setStyleSheet(style)

        self.objectGroup = QtGui.QGroupBox(self)
        self.objectGroup.setLayout(QtGui.QVBoxLayout())
        self.objectTree = ObjectTreeWidget(self, main=self)
        self.findLineEdit = QtGui.QLineEdit()
        self.findLineEdit.setSizePolicy(QtGui.QSizePolicy.Expanding, 
                                        QtGui.QSizePolicy.Maximum)
        self.objectGroup.layout().setSpacing(0)
        self.objectGroup.layout().setMargin(0)
        self.objectGroup.layout().addWidget(self.findLineEdit)
        self.objectGroup.layout().addWidget(self.objectTree)

        # tree widgets
        self.propertyTree = PropertyTreeWidget(self)
        self.sampleTree = SampleTreeWidget(self)
        self.arrayTree = ArrayTreeWidget(self)

        # console
        self.console = AbcConsoleWidget(self)
        self.console.updateNamespace({
            'help': self.console.handleHelp,
            'exit': self.console.exit,
            'find': self.find,
            'objects': self.objectTree,
            'properties': self.propertyTree,
            'samples': self.sampleTree,
            'alembic': alembic
            })

        # signals
        self.connect(self.objectTree, QtCore.SIGNAL('itemDoubleClicked (PyQt_PyObject)'),
                self.handleDoubleClick)
        self.connect(self.propertyTree, QtCore.SIGNAL('itemDoubleClicked (PyQt_PyObject)'),
                self.handleDoubleClick)
        self.connect(self.sampleTree, QtCore.SIGNAL('itemDoubleClicked (PyQt_PyObject)'),
                self.handleDoubleClick)
        self.propertyTree.connect(self.objectTree, QtCore.SIGNAL('itemClicked (PyQt_PyObject)'), 
                self.handleProperties)
        self.sampleTree.connect(self.propertyTree, QtCore.SIGNAL('itemClicked (PyQt_PyObject)'), 
                self.handleSamples)
        self.arrayTree.connect(self.sampleTree, QtCore.SIGNAL('itemClicked (PyQt_PyObject)'), 
                self.arrayTree.showValues)
        self.connect(self.findLineEdit, QtCore.SIGNAL("returnPressed ()"), 
                self.handleFind)

        # viewer
        self.viewer = AbcGLWidget(self)
        self.viewer.signalSceneError.connect(self.handleViewerError)
        self.progressBar = QtGui.QProgressBar(self)
        self.viewerGroup = QtGui.QGroupBox(self)
        self.viewerGroup.setLayout(QtGui.QVBoxLayout())
        self.progressBar.setRange(1, 100)
        self.progressBar.setTextVisible(False)
        self.progressBar.hide()
        self.viewerGroup.layout().setSpacing(0)
        self.viewerGroup.layout().setMargin(0)
        self.viewerGroup.layout().addWidget(self.progressBar)
        self.viewerGroup.layout().addWidget(self.viewer)

        # splitters
        self.mainSplitter = QtGui.QSplitter(QtCore.Qt.Vertical, self)
        self.consoleSplitter = QtGui.QSplitter(QtCore.Qt.Vertical, self)
        self.objectSplitter = QtGui.QSplitter(QtCore.Qt.Horizontal, self)
        self.objectSplitter.addWidget(self.objectGroup)
        self.objectSplitter.addWidget(self.viewerGroup)
        self.propertySplitter = QtGui.QSplitter(QtCore.Qt.Horizontal, self)
        self.propertySplitter.addWidget(self.propertyTree)
        self.propertySplitter.addWidget(self.sampleTree)
        self.propertySplitter.addWidget(self.arrayTree)
        self.mainSplitter.addWidget(self.objectSplitter)
        self.mainSplitter.addWidget(self.propertySplitter)
        self.consoleSplitter.addWidget(self.mainSplitter)
        self.consoleSplitter.addWidget(self.console)
        self.setCentralWidget(self.consoleSplitter)

        # restore state
        self.settings = QtCore.QSettings('Alembic', 'AbcView')
        self.restoreGeometry(self.settings.value('geometry').toByteArray())
        self.restoreState(self.settings.value('windowState').toByteArray())
        self.mainSplitter.restoreState(
                self.settings.value('mainSplitter').toByteArray())
        self.objectSplitter.restoreState(
                self.settings.value('objectSplitter').toByteArray())
        self.propertySplitter.restoreState(
                self.settings.value('propertySplitter').toByteArray())
        self.consoleSplitter.restoreState(
                self.settings.value('consoleSplitter').toByteArray())

        if filepath:
            self.setCache(filepath)

    def message(self, message):
        dialog = QtGui.QMessageBox()
        dialog.setText(message)
        dialog.exec_()

    def setCache(self, filepath):
        try:
            self.cache = alembic.Abc.IArchive(filepath)
        except Exception, e:
            self.message(str(e))

        item = ObjectTreeWidgetItem(self.objectTree, self.cache.getTop())
        self.objectTree.addTopLevelItem(item)

        # set console context info
        self.console.updateNamespace({'archive': self.cache})

        # load the scene into the viewer
        self.viewer.openScene(filepath)

    def find(self, name):
        self.objectTree.find(name)

    def handleViewerProgress(self, value):
        self.progressBar.setValue(value)

    def handleViewerError(self, msg):
        self.progressBar.setValue(0)
        self.progressBar.hide()
        self.message(msg)

    def handleViewerDone(self, processWid):
        self.proc, self.wid = processWid
        self.viewer.embedClient(self.wid)
        self.progressBar.hide()

    def handleFind(self, text=None):
        if text is None:
            text = self.findLineEdit.text()
        if text:
            self.find(str(text.toAscii()))

    def handleDoubleClick(self, item):
        h = self.objectSplitter.size().height()
        w = self.size().width()
        if type(item) == ObjectTreeWidgetItem:
            if self.propertySplitter.size().height() <= 0:
                d = self.objectSplitter.size().height() / 2
                self.mainSplitter.moveSplitter(h - d, 1)
        elif type(item) == PropertyTreeWidgetItem:
            if self.sampleTree.size().width() <= 0:
                d = self.propertySplitter.size().width() / 2
                self.propertySplitter.moveSplitter(w - d, 1)
        elif type(item) == SampleTreeWidgetItem:
            if self.arrayTree.size().width() <= 0:
                d = self.propertySplitter.size().width() / 3
                self.propertySplitter.moveSplitter(w - d, 2)

    def handleProperties(self, item):
        self.sampleTree.clear()
        self.arrayTree.clear()
        self.propertyTree.showProps(item)

    def handleSamples(self, item):
        self.arrayTree.clear()
        self.sampleTree.showSamples(item)

    def toggleConsole(self):
        h = self.size().height()
        if self.console.size().height() == 0:
            self.consoleSplitter.moveSplitter(h - 100, 1)
        else:
            self.consoleSplitter.moveSplitter(h, 1)

    def closeEvent(self, evt):
        self.settings.setValue("geometry", self.saveGeometry())
        self.settings.setValue("windowState", self.saveState())
        self.settings.setValue("mainSplitter", self.mainSplitter.saveState())
        self.settings.setValue("objectSplitter", self.objectSplitter.saveState())
        self.settings.setValue("propertySplitter", self.propertySplitter.saveState())
        self.settings.setValue("consoleSplitter", self.consoleSplitter.saveState())
        evt.accept()
        QtGui.QMainWindow.closeEvent(self, evt)
        if hasattr(self, "proc"):
            self.proc.kill()

def main(filepath):
    app = QtGui.QApplication(sys.argv)
    win = AbcView(filepath)
    win.show()
    win.raise_()
    return app.exec_()

if __name__ == '__main__':
    try:
        filepath = None
        if len(sys.argv) == 2:
            filepath = sys.argv[1]
        else:
            print "%s <file.abc>" % sys.argv[0]
            sys.exit(1)
        sys.exit(main(filepath))
    except Exception, e:
        traceback.print_exc()
    except KeyboardInterrupt:
        print 'Stopping...'
        sys.exit(1)
